package com.huabo.monitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.ImportOrExportExcelUtil;
import com.hbfk.util.JsonBean;
import com.huabo.monitor.entity.*;
import com.huabo.monitor.service.*;
import com.huabo.monitor.util.ConstClass;
import com.huabo.monitor.util.PageBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author：yhr
 * @date:2022-09-15 13:00
 * @description:
 */
@RestController
@Slf4j
@Api(value = "内控测试-测试结果", tags = {"内控测试-测试结果所有接口"})
public class CsjgController {


    @Resource
    ITblTestplanService testplanService;
    @Autowired
    ITblStaffService iTblStaffService;


    @Autowired
    TblAssessService tblAssessService;

    @Resource
    CsfaService csfaService;
    @Resource
    CsjgService csjgService;

    @Resource
    ITblTestelementService iTblTestelementService;
    @Resource
    CsrwService csrwService;

    @Resource
    ITblTesttaskService testtaskService;

    @Resource
    ITblAttachmentService attachmentService;
    @Resource
    ITblTesttaskAttService testtaskAttService;

    @ApiOperation("测试结果-主页")
    @GetMapping(value = "/nkcs/statistic/result_count_list")
    public JsonBean nkcs_result_count_list(

            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,

            @ApiParam(name = "planname", value = "planname") @RequestParam(value = "planname", required = false) String planname,

            @ApiParam(name = "year", value = "year") @RequestParam(value = "year", required = false) String year,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        TblTestplan plan = new TblTestplan();
        if (StringUtils.isNotBlank(planname)) {
            plan.setPlanname(planname);
        }

        if (StringUtils.isNotBlank(year)) {
            plan.setPlanyear(year);
        }

        TblStaffUtil user = DealUserToken.parseUserToken(token);
//        TblOrganization attribute = (TblOrganization) request.getSession().getAttribute("hbOrgEntity");// 选则的机构
//        TblStaff user = (TblStaff) request.getSession().getAttribute("longUser");

        boolean bool = csfaService.isSJByOrgId(user.getLinkDetp().getOrgid().toString());
        IPage<Map<String, Object>> iPage;
        if (bool) {
            iPage = csjgService.findAllCSHZ(plan, pageNumber, user.getCurrentOrg().getOrgid());
        } else {
            iPage = csjgService.findAllWCSjCSHZ(plan, pageNumber,
                    user.getStaffid());
        }


        Map<String, Object> mv = new HashMap<>();
        mv.put("pageBean", iPage);
        mv.put("plan", plan);
        return new JsonBean(200, "success", mv);


    }


    @ApiOperation("测试结果-主页列表点击控制数-左侧树(非json,子节点单独node)")
    @GetMapping(value = "/csjg/gettree_all")
    public JsonBean gettree_all(
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }


        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("planid", planid);

        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("templId", plan.getTesttemid());
                List<Tree> tree = this.csfaService.getTreeC(plan.getTesttemid());
                mv.put("tree", tree);

            }
        }

        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-主页列表点击有效数-左侧树(json树)")
    @GetMapping(value = "/csjg/gettree_yx")
    public JsonBean gettree_yx(
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("planid", planid);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("templId", plan.getTesttemid());
                List<Tree> tree = this.csjgService.getTreeLeftyx(plan.getTesttemid().toString(), planid, "/nbkz/csjg/def_list_yx", user.getStaffid().toString());
                mv.put("tree", tree);

            }
        }
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-主页列表点击无效数-左侧树(json树)")
    @GetMapping(value = "/csjg/gettree_wx")
    public JsonBean gettree_wx(
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("planid", planid);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("templId", plan.getTesttemid());
                List<Tree> tree = this.csjgService.getTreeLeftwx(plan.getTesttemid().toString(), planid, "/nbkz/csjg/def_list_wx", user.getStaffid().toString());
                mv.put("tree", tree);

            }
        }
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-主页列表点击不适用数-左侧树(json树)")
    @GetMapping(value = "/csjg/gettree_bxy")
    public JsonBean gettree_bxy(
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,

            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("planid", planid);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("templId", plan.getTesttemid());
                List<Tree> tree = this.csjgService.getTreeLeftbxy(plan.getTesttemid().toString(), planid, "/nbkz/csjg/def_list_bxy", user.getStaffid().toString());
                mv.put("tree", tree);

            }
        }
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-控制数-点击左侧树(非json,子节点单独node)-右侧列表")
    @GetMapping(value = "/csjg/def_list_all")
    public JsonBean def_list_all(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "左侧树id") @RequestParam(value = "node") String node,
            @ApiParam(name = "templId", value = "templId") @RequestParam(value = "templId") String templId,
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        if (StringUtils.isNotBlank(templId) && StringUtils.isNotBlank(node)) {
            page = this.csjgService.fingByTreeCSRW(node, templId, planid, pageNumber);
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);
        mv.put("pageBean", page);
        return new JsonBean(200, "success", mv);
    }

    /**
     * 测试汇总-详细结果
     *
     * @param pageNumber
     * @param planid
     * @return
     */
    @ApiOperation("测试结果-主页列表-点击详细结果")
    @GetMapping(value = "/cshz/xxjg_list")
    public JsonBean xxjg_list(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "planid", value = "planid", defaultValue = "200685") @RequestParam(value = "planid") BigDecimal planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        if (planid != null) {
            page = csjgService.findAllnoSjResult(planid, pageNumber);
        }

        Map<String, Object> mv = new LinkedHashMap<>();

        mv.put("planid", planid);
        mv.put("pageBean", page);
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-有效树-点击左侧树(json树)-右侧列表")
    @GetMapping(value = "/csjg/def_list_yx")
    public JsonBean def_list_yx(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "左侧树id") @RequestParam(value = "node") String node,
            @ApiParam(name = "templId", value = "templId") @RequestParam(value = "templId", required = false) String templId,
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);

        page = this.csjgService.fingByTreeCSJGY(node, templId, planid, pageNumber);

        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);
        mv.put("pageBean", page);
        return new JsonBean(200, "success", mv);
    }


    @ApiOperation("测试结果-无效数-点击左侧树(json树)-右侧列表")
    @GetMapping(value = "/csjg/def_list_wx")
    public JsonBean def_list_wx(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "左侧树id") @RequestParam(value = "node") String node,
            @ApiParam(name = "templId", value = "templId") @RequestParam(value = "templId") String templId,
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        if (StringUtils.isNotBlank(templId) && StringUtils.isNotBlank(node)) {
            page = this.csjgService.fingByTreeCSJGW(node, templId, planid, pageNumber);
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);
        mv.put("pageBean", page);
        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-不适用数-点击左侧树(json树)-右侧列表")
    @GetMapping(value = "/csjg/def_list_bxy")
    public JsonBean def_list_bxy(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "左侧树id") @RequestParam(value = "node") String node,
            @ApiParam(name = "templId", value = "templId") @RequestParam(value = "templId") String templId,
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        if (StringUtils.isNotBlank(templId) && StringUtils.isNotBlank(node)) {
            page = this.csjgService.fingByTreeCSJGB(node, templId, planid, pageNumber);
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);
        mv.put("pageBean", page);
        return new JsonBean(200, "success", mv);
    }


    @GetMapping(value = "/csrw/control_test_impl_detail")
    @ResponseBody
    @ApiOperation("测试结果-点击数量-点击左侧树-右侧列表-点击编号查询测试结果((通用))")
    public JsonBean control_test_impl_detail(
            @ApiParam(name = "elementId", value = "elementId", defaultValue = "200682") @RequestParam(value = "elementId") BigDecimal ementid,
            @ApiParam(name = "planid", value = "planid", defaultValue = "200685") @RequestParam(value = "planid") BigDecimal planid,
            @ApiParam(name = "node", value = "node只做回传,可以不传", defaultValue = "") @RequestParam(value = "node", required = false) String node,
            @ApiParam(name = "templId", value = "templId只做回传,可以不传", defaultValue = "") @RequestParam(value = "templId", required = false) String templId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        if (ementid != null && planid != null) {
            QueryWrapper<TblTesttask> qw = new QueryWrapper<>();
            qw.eq("elementid", ementid).eq("planid", planid);


            TblTesttask task = this.testtaskService.getOne(qw);
            TblTestelement element = this.iTblTestelementService.getById(ementid);
            List<TblAttachment> atts = attachmentService.findtTblAttachmentByTask(task.getTesttaskid());
            mv.put("element", element);
            mv.put("task", task);
            mv.put("atts", atts);
        }

        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);


        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-详细结果列表-点击数量-左侧树")
    @GetMapping(value = "/cshz/gettree")
    public JsonBean cshz_getTree(
            @ApiParam(name = "planid", value = "testplanid", defaultValue = "200685") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "userid", value = "CPUSERID", defaultValue = "200440") @RequestParam(value = "userid") String userid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("planid", planid);
        mv.put("userid", userid);
        if (StringUtils.isNotBlank(planid)) {
            TblTestplan plan = this.testplanService.getById(new BigDecimal(planid));

            if (plan != null) {
                mv.put("templId", plan.getTesttemid());
                List<Tree> tree = this.csjgService.getTreeCSHZByChilds(plan.getTesttemid().toString(), userid, planid);
                mv.put("tree", tree);

            }
        }
        return new JsonBean(200, "success", mv);

    }



    @ApiOperation("测试结果-详细结果列表-点击数量-右侧列表")
    @GetMapping(value = "/cshz/def_list")
    public JsonBean cshz_gzdg_def_list(
            @ApiParam(name = "pageNumber", value = "pageNumber", defaultValue = "1") @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
            @ApiParam(name = "node", value = "左侧树id") @RequestParam(value = "node") String node,
            @ApiParam(name = "templId", value = "templId") @RequestParam(value = "templId") String templId,
            @ApiParam(name = "planid", value = "testplanid") @RequestParam(value = "planid") String planid,
            @ApiParam(name = "userid", value = "CPUSERID") @RequestParam(value = "userid") String userid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        IPage<Map<String, Object>> page = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        if (StringUtils.isNotBlank(templId) && StringUtils.isNotBlank(node)) {
            page = this.csjgService.fingByTreeCSHZByUser(node, templId, planid, userid, pageNumber);
        }
        Map<String, Object> mv = new LinkedHashMap<>();
        mv.put("node", node);
        mv.put("templId", templId);
        mv.put("planid", planid);
        mv.put("userid", userid);
        mv.put("pageBean", page);

        return new JsonBean(200, "success", mv);
    }


    /**
     * 测试汇总-保存退回意见
     *
     * @param
     * @param planid
     * @return
     */
    @ApiOperation("测试结果-详细结果列表-点击数量-右侧列表-退回-保存")
    @PostMapping(value = "/cshz/task_save")
    public JsonBean cshz_task_save(
            @ApiParam(name = "userid", value = "userid") @RequestParam(value = "userid")String userid,
            @ApiParam(name = "planid", value = "planid") @RequestParam(value = "planid")String planid,
            @ApiParam(name = "taskid", value = "TESTTASKID来自行内数据") @RequestParam(value = "taskid")String taskid,
            @ApiParam(name = "proposal", value = "退回意见") @RequestParam(value = "proposal",required = false)String proposal,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        if (StringUtils.isNotBlank(taskid)) {

            this.csjgService.saveBack(taskid,proposal,planid,userid);


        }
        Map<String, Object> mv = new LinkedHashMap<>();

        mv.put("taskid", taskid);
        mv.put("planid", planid);
        mv.put("userid", userid);

        return new JsonBean(200, "success", mv);
    }

    @ApiOperation("测试结果-详细结果列表-导出excel")
    @GetMapping(value = "/nkcs/result_export")
    public @ResponseBody
    String sjfx_export(
            @ApiParam(name = "planid", value = "planid") @RequestParam(value = "planid")String planid,
            HttpServletResponse response) {

        log.info("内控合规---内控测试---测试结果汇总---导出Excel");
        response.setContentType("application/binary;charset=UTF-8");
        try {
            String name = new String("测试结果".getBytes(), "iso-8859-1");
            String date = String.valueOf(System.currentTimeMillis());
            String fileName = name + "_" + date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            //查询所有测试结果
            List<Object[]> objList = this.csjgService.findElementByPlanid(planid);
            String[] titles = {"测试项目", "编号", "业务描述", "风险描述", "控制目标", "控制措施", "检查方法", "测试程序", "测试结果", "测试有效性"};
            ImportOrExportExcelUtil.exportExcel(titles, objList, outputStream, null);
        } catch (Exception e) {
            log.info("内控合规---内控测试---测试结果汇总---导出Excel失败");
        }
        return null;
    }

}
